//
//  TTIClient.m
//  AFNetWorkingDemo
//
//  Created by zym on 14-8-8.
//  Copyright (c) 2014年 翔傲信息科技（上海）有限公司. All rights reserved.
//

#import "TTIClientManager.h"
#import "TTIClientConfig.h"
#import <AFNetworkActivityLogger.h>
#import <AFNetworkActivityIndicatorManager.h>
#import "AppMacro.h"


@interface TTIClientManager ()

@end


@implementation TTIClientManager


-(id)init{
    self = [super init];
    if (self) {
        //设置baseurl
//        self.manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:NET_BASEURL]];
        self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:NET_BASEURL]];
        
        //AF2.0默认是使用AFJSONResponseSerializer自行对JSON进行解析。（如果请求成功，但是JSON无法解析，错误代码为3840）
        //想要AF2.0使用第三方解析，那么需要将设置为AFHTTPResponseSerializer即可，那么返回值为respondata，需要自己解析。
        _manager.responseSerializer = [AFJSONResponseSerializer serializer];
        _manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        
        //AF2.0只支持text/json，application/json，text/javascript三种格式，如果需要支持其他格式，请自行添加。
        _manager.responseSerializer.acceptableContentTypes = [_manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        
//        [[AFNetworkActivityLogger sharedLogger] setLevel:AFLoggerLevelDebug];
//        [[AFNetworkActivityLogger sharedLogger] startLogging];
        
        [[AFNetworkActivityLogger sharedLogger] setLogLevel:AFLoggerLevelDebug];
        [[AFNetworkActivityLogger sharedLogger] startLogging];
    }
    return self;
}


-(void)parseResponse:(id)responseObject
           operation:(NSURLSessionTask *)task
             success:(void(^)(NSURLSessionTask *task,id responseObject))success
             failure:(void(^)(NSURLSessionTask *task,id responseObject))failure{
    
    if (task.error) {
        
        if (task.error.code == 3840) {
            failure(task,[NSDictionary dictionaryWithObjects:@[@"3804", @"数据格式错误"] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }else if (task.error.code == -1004)
        {
            failure(task,[NSDictionary dictionaryWithObjects:@[@"-1004", @"无法连接到服务器"] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }else
        {
            NSString *code = [NSString stringWithFormat:@"%ld",(long)task.error.code];
            failure(task,[NSDictionary dictionaryWithObjects:@[code, task.error.localizedDescription] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }
    }else{
        NSDictionary *responseDic = (NSDictionary *)responseObject;
        
        long ecode = [[responseDic objectForKey:@"ecode"] integerValue];
        
        if (ecode != 0) {
            if (failure) {
                failure(task,responseDic);
                if (ecode == 998 ||ecode == 997){
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        // 返回登录界面
                        [ICUser logoff];
                        
                    });
                }
            }
            return;
        }
        
        
        if (![responseDic isKindOfClass:[NSDictionary class]] || ![responseDic objectForKey:NET_SUCCESS]) {
            failure(task,[NSDictionary dictionaryWithObjects:@[@"401", NET_NETWORKERROR_TXT] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }
        
        if ([[responseDic objectForKey:NET_SUCCESS] integerValue] ==1 )
        {
            DLOG(@"responseDic === %@",responseDic);
            if (success)
            {
                success(task,[responseDic objectForKey:NET_RESULT]);
                return;
                
            }
            
        }else{
            if (failure) {
                failure(task,responseDic);
                
                //                NSString *str = [NSString stringWithFormat:@"%@",[responseDic objectForKey:NET_ERROR_MSG]];
                // GY add 2017.12.20
                /*
                 if ([str isEqualToString:@"你的帐号已在别处登录，请重新登录"] || [str isEqualToString:@"你的帐号已冻结，请重新登录"]) {
                 
                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 
                 // 返回登录界面
                 [ICUser logoff];
                 
                 [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"login_out"];
                 SGLoginVC *loginVC = ViewControllerWithNameAndIdentifier(@"SGLogin", @"SGLoginVC");
                 TTINavigationController *nav = [[TTINavigationController alloc] initWithRootViewController:loginVC];
                 [UIApplication sharedApplication].keyWindow.rootViewController = nav;
                 
                 });
                 }*/
                // end
                
                return;
            }
        }
    }
    
}

/*
-(void)parseResponse:(id)response
           operation:(AFHTTPRequestOperation *)operation
           success:(void(^)(AFHTTPRequestOperation *operetion,id response))success
           failure:(void(^)(AFHTTPRequestOperation *operetion,id response))failure{
    
    if (operation.error) {
        
        if (operation.error.code == 3840) {
            failure(operation,[NSDictionary dictionaryWithObjects:@[@"3804", @"数据格式错误"] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }else if (operation.error.code == -1004)
        {
            failure(operation,[NSDictionary dictionaryWithObjects:@[@"-1004", @"无法连接到服务器"] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }else
        {
            NSString *code = [NSString stringWithFormat:@"%ld",(long)operation.error.code];
            failure(operation,[NSDictionary dictionaryWithObjects:@[code, operation.error.localizedDescription] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }
    }else{
        NSDictionary *responseDic = (NSDictionary *)response;
        
        if (![responseDic isKindOfClass:[NSDictionary class]] || ![responseDic objectForKey:NET_SUCCESS]) {
            failure(operation,[NSDictionary dictionaryWithObjects:@[@"401", NET_NETWORKERROR_TXT] forKeys:@[NET_SUCCESS, NET_ERROR_MSG]]);
            return;
        }
        
        if ([[responseDic objectForKey:NET_SUCCESS] integerValue] ==1 )
        {
            DLOG(@"responseDic === %@",responseDic);
            if (success)
            {
                success(operation,[responseDic objectForKey:NET_RESULT]);
                return;

            }

        }else{
            if (failure) {
                failure(operation,responseDic);
                return;
            }
        }
    }

}
 
 */

+(void)addParamSignForCaptcha:(NSMutableDictionary *)paramDict
{
    
}

@end


